package com.ray.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.appengine.api.files.FileServicePb.ListDirRequest;
import com.google.appengine.api.search.query.ExpressionParser.index_return;
import com.google.appengine.api.search.query.ExpressionParser.name_return;
import com.google.appengine.api.search.query.ExpressionParser.negation_return;
import com.google.appengine.repackaged.com.google.protobuf.Internal.DoubleList;
import com.mchange.v2.async.StrandedTaskReporting;
import com.ray.bean.*;
import com.ray.bean.MachinepRrocessCapacityBean.DayCapacity;
import com.ray.exception.ServiceException;
import com.ray.mapper.*;
import com.ray.pojo.EquipmentBoardPojo;
import com.ray.pojo.EquipmentDetail;
import com.ray.pojo.EquipmentDetailPojo;
import com.ray.pojo.EquipmentRecordPojo;
import com.ray.pojo.ShowEquipmentPojo;
import com.ray.protocol.constants.EnergyStatus;
import com.ray.util.ParamUtil;
import com.ray.util.ReturnStringUtil;
import com.ray.util.StringUtil;
import com.ray.util.TimeAndUnix;
import com.ray.util.redis.RedisCache;
import com.ray.util.redis.RedisKey;

import net.sf.json.JSONArray;

import org.apache.ibatis.annotations.Case;
import org.apache.poi.ss.formula.functions.PPMT;
import org.apache.xmlbeans.impl.xb.xsdschema.NarrowMaxMin;
import org.joda.time.DateTime;
import org.junit.Ignore;
import org.quartz.spi.InstanceIdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.io.FileOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import javax.mail.search.IntegerComparisonTerm;
import javax.management.relation.InvalidRelationTypeException;
import javax.print.attribute.standard.RequestingUserName;

@SuppressWarnings("unchecked")
@Service
public class EquipmentService {

    @Autowired
    EquipmentMapper equipmentMapper;
    @Autowired
    DepartmentMapper departmentMapper;
    @Autowired
    EnergyService energyService;
    @Autowired
    TemporalIntervalMapper temporalIntervalMapper;
    @Autowired
    MachineMapper machineMapper;
    @Autowired
    MachineRelationProcessMapper machineRelationProcessMapper;
    @Autowired
    MachineRelationWorkingTimeIntervalMapper machineRelationWorkingTimeIntervalMapper;
    @Autowired
    InternetThingCardService internetThingCardService;

    /**
     * @return void
     * @throws ServiceException 新增设备信息表
     * @throws
     * @date 2018年4月12日 上午9:46:39
     * @author 李斌
     */
    
    private static  final String equipmentBoardKey ="equipmentBoard";

    public void addEquipment(Map map) throws ServiceException {
        MachineBean machineBean = new MachineBean();
        machineBean.setCompany(map.get("loginCompany").toString());
        machineBean.setEquipmentNo(map.get("equipmentNo").toString());
        machineMapper.addMachine(machineBean);
        machineBean = equipmentMapper.getMachineByEquipmentNo(map.get("equipmentNo").toString());
        Map paramMap = new HashMap();
        paramMap.put("id", map.get("energyId"));
        if (!"".equals(paramMap.get("id"))) {
            EnergyBean energyBean = energyService.getEnergy(paramMap);
            if (energyBean.used()) {
                throw new ServiceException("电表已被分配，请选择其他电表");
            } else {
                paramMap.put("state", 1);
                energyService.updateState(paramMap);
            }
        }
        
        /**
         * 有设设置物联网卡id
         */
        if(!"".equals(map.get("internetThingsCard")) && null!=map.get("internetThingsCard")) {
        	boolean bool=internetThingCardService.checkCardIsRepeat(map);
        	Assert.isTrue(!bool,"物联网卡不存在");
        	boolean boolea=this.checkInternetIsRelation(map);
        	Assert.isTrue(boolea,"物联网卡已经使用过,不可再次使用");
        }

        paramMap.clear();
        paramMap.put("id", map.get("flowId"));
        if (!"".equals(paramMap.get("id"))) {
            EnergyBean energyBean = energyService.getEnergy(paramMap);
            if (energyBean.used()) {
                throw new ServiceException("气表已被分配，请选择其他气表");
            } else {
                paramMap.put("state", 1);
                energyService.updateState(paramMap);
            }
        }
        if(null!=map.get("workTimeIntervals")) {
        	List<String> workTimeIntervals = JSON.parseArray(
        			map.get("workTimeIntervals").toString(), String.class);
        	if(workTimeIntervals.size()>0) {
        		handleWorkTimeIntervals(workTimeIntervals, machineBean);
        	}
        	
        }
        if(null!=map.get("processBeans")) {
        	List<String> processBeans = JSON.parseArray(map.get("processBeans")
        			.toString(), String.class);
        	if(processBeans.size()>0) {
        		handleMachineRelationProcess(machineBean, processBeans);
        	}
        }
        
        machineBean.setMainSwitch(map.get("mainSwitch").toString());
        machineBean.setIsHandOperation(map.get("isHandOperation").toString());
        if(null!=map.get("timeoutBreakElectricityTime"))
        machineBean.setTimeoutBreakElectricityTime(map.get("timeoutBreakElectricityTime").toString());
        if(null!=map.get("timeoutBreakFlowTime"))
        machineBean.setTimeoutBreakFlowTime(map.get("timeoutBreakFlowTime").toString());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");
        map.put("id", StringUtil.getUUID());
        map.put("createTime", sdf.format(new Date()));
        if(null!=map.get("purchaseTime"))
        map.put("purchaseTime", map.get("purchaseTime"));
        machineMapper.updateMachine(machineBean);
        equipmentMapper.addEquipment(map);
    }

    private void handleMachineRelationProcess(MachineBean machineBean,
                                              List<String> processBeans) {
        List<MachineRelationProcessBean> machineRelationProcessBeans = new ArrayList<>();
        for (String processBeanJson : processBeans) {
            JSONObject jsonObject = JSON.parseObject(processBeanJson);
            machineRelationProcessBeans.add(new MachineRelationProcessBean(
                    jsonObject.getString("process"), jsonObject
                    .getString("maxProcessTime"), machineBean.getId()));
        }

        for (MachineRelationProcessBean machineRelationProcessBean : machineRelationProcessBeans) {
            if (machineRelationProcessMapper
                    .getMachineRelationProcessBeanByMachineIDAndProcessIdentify(machineRelationProcessBean) == null) {
                machineRelationProcessMapper
                        .addMachineRelationProcess(machineRelationProcessBean);
            }
        }
    }

    private void handleWorkTimeIntervals(List<String> workTimeIntervals,
                                         MachineBean machineBean) {
        List<TemporalIntervalBean> temporalIntervalBeans = new ArrayList<>();
        for (String temporalInterval : workTimeIntervals) {
            JSONObject jsonObject = JSON.parseObject(temporalInterval);
            temporalIntervalBeans.add(new TemporalIntervalBean(jsonObject
                    .getString("startTime"), jsonObject.getString("endTime")));
        }
        for (TemporalIntervalBean temporalIntervalBean : temporalIntervalBeans) {
            String temporalIntervalId = temporalIntervalMapper
                    .getTemporalIntervalId(temporalIntervalBean.getStartTime(),
                            temporalIntervalBean.getEndTime());

            if (temporalIntervalId != null) {
                if (machineRelationWorkingTimeIntervalMapper
                        .getMachineRelationWorkingTimeIntervalByMachineIDAndTemporalIntervalId(
                                machineBean.getId(), temporalIntervalId) != null) {
                    continue;
                } else {
                    MachineRelationWorkingTimeIntervalBean machineRelationWorkingTimeIntervalBean =
                            new MachineRelationWorkingTimeIntervalBean(machineBean.getId(), temporalIntervalId);
                    machineRelationWorkingTimeIntervalMapper
                            .addMachineRelationWorkingTimeInterval(machineRelationWorkingTimeIntervalBean);
                }
            } else {
                temporalIntervalMapper
                        .insertTemporalInterval(temporalIntervalBean);
                MachineRelationWorkingTimeIntervalBean machineRelationWorkingTimeIntervalBean =
                        new MachineRelationWorkingTimeIntervalBean(machineBean.getId(), temporalIntervalBean.getTimeIntervalId());
                machineRelationWorkingTimeIntervalMapper
                        .addMachineRelationWorkingTimeInterval(machineRelationWorkingTimeIntervalBean);
            }
        }
    }

    /**
     * 通过设备信息获取设备
     *
     * @return void
     * @throws
     * @date 2018年4月12日 上午10:12:18
     * @author 李斌
     */
    public List<EquipmentBean> getEquipmentByDetail(Map map) {
        return equipmentMapper.getEquipmentByDetail(map);
    }

    /**
     * @return void
     * @throws ServiceException 修改设备信息息
     * @throws
     * @date 2018年4月12日 下午1:59:44
     * @author 李斌
     */
    public void updateEquipment(Map map) throws ServiceException {
        EquipmentBean oldEquipmentBean = equipmentMapper
                .getEquipmentByMachineId(map.get("id").toString());
        if (oldEquipmentBean != null) {
            map.put("id", oldEquipmentBean.getId());
            
            /**
             * 有设设置物联网卡id
             */
            if(!"".equals(map.get("internetThingsCard")) && null!=map.get("internetThingsCard")) {
            	boolean bool=internetThingCardService.checkCardIsRepeat(map);
            	Assert.isTrue(!bool,"物联网卡不存在");
            	boolean boolea=this.checkInternetIsRelation(map);
            	Assert.isTrue(boolea,"物联网卡已经使用过,不可再次使用");
            }
            
            int flag = equipmentMapper.updateEquipment(map);
            if (flag <= 0) {
                throw new ServiceException("修改失败");
            }
            // 如果有对电表做修改
            String energyId = map.get("energyId").toString();
            String flowId = map.get("flowId").toString();
            handleEnergy(oldEquipmentBean.getEnergyId(), energyId, "电表");
            handleEnergy(oldEquipmentBean.getFlowId(), flowId, "气表");
        }
        MachineBean machineBean = equipmentMapper.getMachineByEquipmentNo(map.get("equipmentNo").toString());
        machineBean.setMainSwitch(map.get("mainSwitch").toString())
                .setIsHandOperation(map.get("isHandOperation").toString())
                .setTimeoutBreakElectricityTime(map.get("timeoutBreakElectricityTime").toString())
                .setTimeoutBreakFlowTime(map.get("timeoutBreakFlowTime").toString());
        machineMapper.updateMachine(machineBean);
        List<String> workTimeIntervals = JSON.parseArray(map.get("workTimeIntervals").toString(), String.class);
        List<String> processBeans = JSON.parseArray(map.get("processBeans").toString(), String.class);
        machineRelationProcessMapper.delMachineRelationProcessByMachineId(machineBean.getId());
        machineRelationWorkingTimeIntervalMapper.delMachineRelationWorkingTimeIntervalByMachineId(machineBean.getId());
        handleWorkTimeIntervals(workTimeIntervals, machineBean);
        handleMachineRelationProcess(machineBean, processBeans);
    }
    
    
//    查询物联网卡是否关联过设备
    public boolean checkInternetIsRelation(Map map) {
    	//如果有传互联网卡id
    	if(map.get("internetThingsCard")!=null && !"".equals(map.get("internetThingsCard").toString())) {
    		Map map2=new HashMap();
    		map2.put("internetThingsCard", map.get("internetThingsCard"));
    		map2.put("equipmentNo", map.get("equipmentNo"));
    		map2.put("id", map.get("id"));
    		int  selfSize=this.checkCountByNo(map2);
    		map2.remove("equipmentNo");
    		map2.remove("id");
    		int  otherSize=this.checkCountByNo(map2);
    		if(otherSize-selfSize>0) {
    			return false;
    		}
    	}
    	return true;
    }

    private void handleEnergy(String oldEnergyId, String energyId, String errorEnergy) {
        if ("".equals(energyId)) {
            if (!("".equals(oldEnergyId))) {
                energyService.freeOrUseEnergy(oldEnergyId, EnergyStatus.FREE);
            }
        } else {
            if (energyId != null && !(energyId.equals(oldEnergyId))) {
                Map<String, Object> paramMap = new HashMap<>(2);
                paramMap.put("id", energyId);
                // 查询表为使用
                paramMap.put("state", 1);
                EnergyBean energyBean = energyService.getEnergy(paramMap);
                if (energyBean != null) {
                    throw new ServiceException(errorEnergy + "已被分配，请选择其他" + errorEnergy);
                }
                // 将修改的表状态改占用
                energyService.updateState(paramMap);
                energyService.freeOrUseEnergy(oldEnergyId, EnergyStatus.FREE);
            }
        }
    }

    /**
     * start(分页参数)
     * length(分页参数)
     * department(部门id)
     * workShop(车间id)
     * @param map
     * @return
     * @throws ParseException
     * @throws ServiceException
     */
    public DatatablesViewPageBean<ShowEquipmentPojo> getAllEquipment(Map map)
            throws ParseException, ServiceException {
        DatatablesViewPageBean<ShowEquipmentPojo> dbvpb = new DatatablesViewPageBean<>();
        int total = equipmentMapper.getAllEquipmentCount(map);
        List<ShowEquipmentPojo> showEquipmentPojos = equipmentMapper
                .getAllShowEquipmentPojo(map);
        dbvpb.setiTotalRecords(total);
        dbvpb.setiTotalDisplayRecords(total);
        dbvpb.setReturnData(showEquipmentPojos);
        return dbvpb;
    }
    
    /**
     * 获取所有设备信息
     * @param map
     * @return
     */
    public List<ShowEquipmentPojo> getAllShowEquipmentPojo(Map map) {
    	return equipmentMapper.getAllShowEquipmentPojo(map);
    }

    
    public List<DepartmentDropdownBean> getDepartmentAndWorkShop(Map map) {
        return departmentMapper.getDepartmentDropdowns(map);
    }

    
    // 检查设备编号
    public int checkCountByNo(Map map) {
        List<EquipmentBean> equipments = equipmentMapper
                .getEquipmentByDetail(map);
        return equipments.size();
    }

    /**
     * 获取设备加工信息
     *
     * @param map
     * @return List<MachineBean>
     * @throws ServiceException departmentId（部门id） workShopId(车间id)
     * @author natelu
     */
    public List<MachineBean> getAllMachine(Map map) {
        return equipmentMapper.getAllMachine(map);
    }

    /**
     * 获取电气监控数据
     *
     * @param request
     * @param departmentId (部门id)
     * @param workShopId   (车间id)
     * @param equipmentNo  (设备编号，查询 单条数据)
     * @param start        (开始条数)
     * @param length       (结束条数)
     * @return
     * @throws ServiceException
     * @author natelu
     */
    public DatatablesViewPageBean<EcsMonitorBean> getEcsMonitor(Map map) {
        DatatablesViewPageBean<EcsMonitorBean> dbvpb = new DatatablesViewPageBean<EcsMonitorBean>();
        dbvpb.setReturnData(equipmentMapper.getEcsMonitorData(map));
        int total = equipmentMapper.getEcsMonitorCount(map);
        dbvpb.setiTotalRecords(total);
        dbvpb.setiTotalDisplayRecords(total);
        return dbvpb;
    }

    /**
     * 设置设备生产订单
     * @param equipmentNo (设备编号)
     * @param orderId     (订单编号)
     * @param orderNo     (加工订单编号)
     * @param request
     * @return
     * @throws ServiceException
     * @author nate
     */
    public void setEquipmentMachineOrder(Map map) throws ServiceException {
    	StringUtil.checkIsTrue(map, "equipmentNo", "未获取到设备编号");
        String equipmentNo = map.get("equipmentNo").toString();// 设备编号
        String orderId = map.get("orderId").toString();// 系统订单编号
        String orderNo = map.get("orderNo").toString();// 加工订单编号
        // 设置此设备电表为采集状态
        equipmentMapper.updateEnergyState(map);
        if (equipmentNo == null || "".equals(equipmentNo)) {
            throw new ServiceException("未获取到设备编号");
        }
        if (orderId == null || "".equals(orderId)) {
            throw new ServiceException("未获取到系统订单编号");
        }
        if (orderNo == null || "".equals(orderNo)) {
            throw new ServiceException("未获取到加工订单编号");
        }

        // 查询在此设备在此公司是否生产过
        Double beforeYield = equipmentMapper.getBeforeYield(map);
        beforeYield = beforeYield == null ? 0 : beforeYield;
        // 加工数量
        map.put("yield", beforeYield);
        // 检查系统订单编号是否相同
        Map paramMap = new HashMap();
        paramMap.put("company", map.get("loginCompany"));
        paramMap.put("equipmentNo", equipmentNo);
        paramMap.put("createUser", map.get("loginUserId"));
        // 订单编号
        paramMap.put("orderId", orderId);
        List<MachineBean> machineList = equipmentMapper.getMachine(paramMap);
        if (machineList != null && machineList.size() > 0) {
            throw new ServiceException("当前生产的订单与人员均相同，无需更换");
        }
        paramMap.remove("orderId");
        // 加工单号
        paramMap.put("orderNo", map.get("orderNo"));
        machineList = equipmentMapper.getMachine(paramMap);
        // 获取电表度数
        Double degee = equipmentMapper.getDegeeByEquipmentNo(paramMap);
        map.put("degee", degee);
        // 如果加工单号不相同
        if (machineList == null || machineList.size() <= 0) {
            // 将设备暂停
            map.put("equipmentAction", 1);
            RedisCache.setDataToRedis("equipmentAction", 1, null);
            // 修改系统单号，并将equipmentAction设为1
            equipmentMapper.insertEquipmentRecordBySchedule(paramMap);
            equipmentMapper.updateSystemOrderNo(map);
//            throw new ServiceException("设置单号与设备单号不符，已暂停设备！！！");
        } else {
            map.put("equipmentAction", 0);
            equipmentMapper.insertEquipmentRecordBySchedule(paramMap);
            // 修改生产订单信息
            equipmentMapper.updateSystemOrderNo(map);
            map.put("company", map.get("loginCompany"));
        }
        equipmentMapper.insertEquipmentRecordBySchedule(map);
        this.setResidMachingOrder(map);
    }
    
    
    
    
    /**
     * 设置redis中的设备加工单号
     * @param map
     */
    public void setResidMachingOrder(Map map) {
    	 String equipmentNo = map.get("equipmentNo").toString();// 设备编号
         Map<String, JSONObject> equipmentBoard = (Map<String, JSONObject>) RedisCache
                 .getDataFromRedis(equipmentBoardKey);
         JSONObject jsonObject=equipmentBoard.get(equipmentNo);
         if(jsonObject != null ) {
        	 jsonObject.put("order", map.get("orderNo"));
        	 jsonObject.put("factoryType", map.get("factoryId"));
        	 jsonObject.put("need", map.get("need"));
        	 jsonObject.put("isChange", "1");//是否是换单
        	 equipmentBoard.put(equipmentNo, jsonObject);
        	 RedisCache.setDataToRedis(equipmentBoardKey, equipmentBoard, null);
         }
    }

    /**
     * 获取设备稼动率
     *
     * @param request
     * @param departmentId (部门id)
     * @param workShopId   (车间id)
     * @param startTime    (开始时间，毫秒数)
     * @param endTime      (结束时间)
     * @param start        (分页参数)
     * @param length       (分页参数)
     * @param equipmentNo  (设备编号，查询 单条数据)
     * @throws ServiceException
     */
    public DatatablesViewPageBean<EquipmentCropMobilityBean> getEquipmentCropMobility(
            Map map) {
        Object startDate = map.get("startTime");
        Object endDate = map.get("endTime");
        if (startDate != null && !"".equals(startDate.toString())) {
            String startTime = TimeAndUnix.haoMiaoToTime(startDate.toString());
            map.put("startTime", startTime);
        }
        if (endDate != null && !"".equals(endDate.toString())) {
            String endTime = TimeAndUnix.haoMiaoToTime(endDate.toString());
            map.put("endTime", endTime);
        }
        DatatablesViewPageBean<EquipmentCropMobilityBean> dbvpb = new DatatablesViewPageBean<>();
        dbvpb.setReturnData(equipmentMapper.getEquipmentCropMobilityData(map));
        int total = equipmentMapper.getEquipmentCropMobilityCount(map);
        dbvpb.setiTotalRecords(total);
        dbvpb.setiTotalDisplayRecords(total);
        return dbvpb;
    }

    public List<EquipmentBean> getNoMainSwitchEquipment(Map map) {
        return equipmentMapper.getNoMainSwitchEquipment(map);
    }

    public Map<String, Object> getNumberOfThrowStuff(String data) {
        JSONObject jsonData = JSONObject.parseObject(data);
        String id = jsonData.getString("id");
        String orderNo = jsonData.getString("orderNo");
        Map<String, Object> result = new HashMap<>();
        //默认返回
        result.put("id", id);
        result.put("orderNo", orderNo);
        result.put("need", 0);
        Queue<String> param = null;
        try {
            param = ParamUtil.getAllNonNullParamsByKeyOrder(jsonData, "orderNo", "company");
        } catch (Exception e) {
            return result;
        }
        Map<String, Object> resultMap = equipmentMapper.getNumberOfThrowStuffByEquipmentNo(param.poll(), param.poll());
        if (resultMap == null) {
            return result;
        }
        resultMap.put("id", id);
        result.put("orderNo", orderNo);
        return resultMap;
    }

    
    /**
     "eqpmt": "sh1001",
     "order": "order001",
     "total": 9999,
     "current": 99,
     "need": 20000,
     "uptime": 7000,
     "timeSingle": 58,
     "debugCount": 4,
     "status": "Run",
     "orderId":"order01",
     "factoryType":"Factory-type"
       alarmId
     * @param data
     * @return
     */
    public Integer pushEquipmentBoardDynamicData(String data) {
    	SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    	String requestTime=simpleDateFormat.format(new Date());
        System.out.println(data);
        
        List<Map> insertMaps = new ArrayList<Map>();
        
        
        try {
        	boolean isClear = false;
            List<JSONObject> jObjects = JSON.parseArray(data, JSONObject.class);
            List<Map<String, Object>> machines = new ArrayList<>();
            Map<String, JSONObject> equipmentBoard = (Map<String, JSONObject>) RedisCache
                    .getDataFromRedis(equipmentBoardKey);
            /**
             * 之前已有的设备编号
             */
            Set<String> oldEqumentNoSet=equipmentBoard.keySet();
            if (equipmentBoard == null) {
                equipmentBoard = new HashMap<>();
            }
           /**
            * 保证传过来的数据，在系统里是有设备编号对应的，没有的不用理会
            */
//            List<EquipmentBean> list=null;
            List<EquipmentBean> list=(List<EquipmentBean>) RedisCache.getDataFromRedis(ReturnStringUtil.SAVE_EQUIMENT_RALATION_INTERNERCARD_KEY);
            if(null==list) {
            	list=equipmentMapper.checkIsHave();
            	RedisCache.setDataToRedis(ReturnStringUtil.SAVE_EQUIMENT_RALATION_INTERNERCARD_KEY, list, ReturnStringUtil.SAVE_EQUIMENT_RALATION_INTERNERCARD_TIME);
            }
            		
            Set<String> equimentNoSet=list.stream().map(EquipmentBean::getEquipmentNo).collect(Collectors.toSet());
            
            /**
             * 遍历传过来的数据
             */
            List<EquipmentAlarmCodeBean> updateDataList=new ArrayList<EquipmentAlarmCodeBean>();
            for (JSONObject eqpmt : jObjects) {
            	Set<String> jsonKeys=eqpmt.keySet();
            	/**
            	 * 将传过来的物联网卡id与设备编号对应
            	 */
            	//如果传过来的json数据有物联网卡id 
            	if(jsonKeys.contains("client_id")) {
            		String fromClientId = eqpmt.getString("client_id");
            		List<EquipmentBean> filter=list.stream().filter(in->fromClientId.equals(in.getInternetThingsCard())).collect(Collectors.toList());
            		if(filter.size()>0) {
            			eqpmt.put("eqpmt", filter.get(0).getEquipmentNo());
            		}else {
            			eqpmt.put("eqpmt", "");
            		}
            		String codeDescribe="";
        			if(jsonKeys.contains("alarmId")) {
        				List<EquipmentAlarmCodeBean> alarmList=(List<EquipmentAlarmCodeBean>) RedisCache.getDataFromRedis(ReturnStringUtil.SAVE_EQUIMENT_ALARM_KEY);
    		            if(null==alarmList) {
    		            	alarmList=equipmentMapper.getAllEquimentAlarmDetail();
    		            	RedisCache.setDataToRedis(ReturnStringUtil.SAVE_EQUIMENT_ALARM_KEY, alarmList, ReturnStringUtil.SAVE_EQUIMENT_ALARM_TIME);
    		            }
    		            Integer alarmCode= eqpmt.getInteger("alarmId");
    		            List<EquipmentAlarmCodeBean>  cordList=alarmList.stream().filter(cc->cc.getInternetThingsCard().equals(fromClientId) && alarmCode==cc.getAlarmCode()).collect(Collectors.toList());
        			    if(cordList.size()<=0) {
        			    	codeDescribe=alarmCode+"";
        			    }else {
        			    	codeDescribe=cordList.get(0).getCodeDescribe();
        			    }
        			}
        			eqpmt.put("codeDescribe", codeDescribe);
        			//如果状态有改变
        			if(jsonKeys.contains("status")) {
        				EquipmentAlarmCodeBean equipmentAlarmCodeBean=new EquipmentAlarmCodeBean();
        				equipmentAlarmCodeBean.setInternetThingsCard(fromClientId);
        				equipmentAlarmCodeBean.setAlarmCode(eqpmt.getInteger("alarmId"));
        				equipmentAlarmCodeBean.setCodeDescribe(codeDescribe);
        				String status=eqpmt.getString("status");
        				switch (eqpmt.getString("status")) {
                    	case "警报":
                    		equipmentAlarmCodeBean.setState("0");
                    		break;
                    	case "待机":
                    		equipmentAlarmCodeBean.setState("1");
                    		break;
                    	case "运行":
                    		equipmentAlarmCodeBean.setState("2");
                    		break;
                    	case "离线":
                    		equipmentAlarmCodeBean.setState("3");
                    		break;
                    	case "暂停":
                    		equipmentAlarmCodeBean.setState("4");
                    		break;
        				}
        				updateDataList.add(equipmentAlarmCodeBean);
        			}
            	}
            	String equipmentNo=eqpmt.getString("eqpmt");
            	
            	
            	
            	/**
            	 * 如果此设备之前有保留数据，更新新的值，没有的不更新
            	 */
            	if(oldEqumentNoSet.contains(equipmentNo)) {
            		JSONObject oldDetail=  equipmentBoard.get(equipmentNo);
            		//旧值
            		int   oldTotal=oldDetail.getInteger("total")==null?0:oldDetail.getInteger("total");
            		int   newTotal=eqpmt.getInteger("total")==null?0:eqpmt.getInteger("total");
            		//如果有清零 或者从今天计数开始  都要保存记录
            		if(newTotal!= 0 && newTotal < oldTotal) {
            			Map beforeMap = new HashMap();
            			beforeMap.put("orderId",oldDetail.get("order") );
            			beforeMap.put("equipmentNo", equipmentNo);
            			beforeMap.put("orderNo", oldDetail.get("order"));
            			beforeMap.put("yield", oldTotal);
            			Map afterMap = new HashMap();
            			afterMap.put("orderId", oldDetail.get("order"));
            			afterMap.put("equipmentNo", equipmentNo);
            			afterMap.put("orderNo", oldDetail.get("order"));
            			afterMap.put("yield", newTotal);
            			insertMaps.add(beforeMap);
            			insertMaps.add(afterMap);
            			isClear = true;
            		}
            		
            		//计数
            		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            		String toDay = sdf.format(new Date());//今天
            		String oldDay = oldDetail.getString("day");
            		int count = oldDetail.getInteger("count")==null?0:oldDetail.getInteger("count");
            		if(!toDay.equals(oldDay)) {//如果日期不是今天计数从0开始
            			oldDetail.put("day", toDay);
            			count =  0;
            		}
            		if(newTotal!= 0 && newTotal != oldTotal) {
            			oldDetail.put("count", count+1);
            		}
            		
            		
            		for(String newKey:jsonKeys) {
            			if("eqpmt".equals(newKey) || "client_id".equals(newKey)) {
            				continue;
            			}
            			//如果有扫码换单，就不更新订单信息
            			if(oldDetail.containsKey("isChange")) {
            				  if("order".equals(newKey) || "factoryType".equals(newKey) || "need".equals(newKey)) {
            					  continue;
            				  }
            			}
            			List<EquipmentBean> maxTimeList= list.stream().filter(pp->equipmentNo.equals(pp.getEquipmentNo())).collect(Collectors.toList());
            			if(maxTimeList.size()>0) {
            				Double processMaxWorkingTime = maxTimeList.get(0).getProcessMaxWorkingTime();
            				oldDetail.put("processMaxWorkingTime", processMaxWorkingTime);
            				oldDetail.put("nowTime", requestTime);
            			}
            			//新的参数有传的就更新   没传的保持不变
            			oldDetail.put(newKey, eqpmt.getString(newKey));
            		}
            		//新旧交换
            		eqpmt=oldDetail;
            	}
                if (jsonKeys.contains("current") &&   eqpmt.getInteger("current") == -1) {
                    eqpmt = equipmentBoard.get(equipmentNo);
                    if(null==eqpmt) {
                    	eqpmt=new JSONObject();
                    	eqpmt.put("eqpmt", equipmentNo);
                    }
                    eqpmt.put("status", "离线");
                }
                equipmentBoard.put(equipmentNo, eqpmt);
            }
            boolean isClearTwo= isClear;
            RedisCache.setDataToRedis(equipmentBoardKey, equipmentBoard, null);
            //重新启动一个线程存储machine数据
            new Thread(() -> {
                for (JSONObject eqpmt : jObjects) {
                	Set<String> keySet=eqpmt.keySet();
                	boolean bool=equimentNoSet.contains(eqpmt.getString("eqpmt"));
                    if ((keySet.contains("current") && eqpmt.getInteger("current") == -1) || !equimentNoSet.contains(eqpmt.getString("eqpmt"))) {
                        continue;
                    }
                    Map<String, Object> machine = new HashMap<>();
                    machine.put("equipmentNo", eqpmt.getString("eqpmt"));
                    machine.put("orderNo", eqpmt.getString("order"));
                    machine.put("systemOrderNo", eqpmt.getString("order"));
                    machine.put("orderId", eqpmt.getString("orderId"));
                    machine.put("alarmId", eqpmt.getString("alarmId"));
                    machine.put("codeDescribe", eqpmt.getString("codeDescribe"));
                    //根据设备状态确定数据库中的设备状态代码
                    if(keySet.contains("status")) {
                    	switch (eqpmt.getString("status")) {
                    	case "警报":
                    		machine.put("state", "0");
                    		break;
                    	case "待机":
                    		machine.put("state", 1);
                    		break;
                    	case "运行":
                    		machine.put("state", 2);
                    		break;
                    	case "离线":
                    		machine.put("state", 3);
                    		break;
                    	case "暂停":
                    		machine.put("state", 4);
                    	}
                    }
                    machine.put("yield", eqpmt.getInteger("total"));
//                    if ((keySet.contains("current") && eqpmt.getInteger("current") == -1)) {
//                        machine.remove("orderNo");
//                        machine.remove("systemOrderNo");
//                        machine.remove("orderId");
//                        machine.remove("yield");
//                    }
                    
                    machine.put("requestTime", requestTime);
                    machines.add(machine);
                }
                machineMapper.updateIntertnetCardState(updateDataList);
                if(machines.size()>0) {
                	machineMapper.updateBatchMachine(machines);
                	machineMapper.insertAtTimeData(machines);
                }
                //如果有清零保存新数据
                if(isClearTwo) {
                	try {
                		equipmentMapper.insertEquipmentRecordByDifferent(insertMaps);
                	}catch(Exception e) {
                		
                	}
                }
                
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
        return 1;
    }

    /**
     * @Author: 李宇航
     * @description : 获取设备看板数据
     * @Param: [param]
     * @return: java.util.List<com.ray.pojo.EquipmentBoardPojo>
     * @Date: 2018/10/29
     */
    public List<EquipmentBoardPojo> getEquipmentBoard(Map<String, String> param) {
        String formatStr = "yyyy-MM-dd";
        String startOfMonth = new DateTime().dayOfMonth().withMinimumValue()
                .withMillisOfDay(0).toString(formatStr);
        param.put("startOfMonth", startOfMonth);
        List<EquipmentBoardPojo>  list= equipmentMapper.getAllEquipmentBoard(param);
        //当日加工时间
        List<EquipmentBoardPojo> dayList = this.getEquipmentDayTime();
        Map<String, JSONObject> equipmentBoard = (Map<String, JSONObject>) RedisCache.getDataFromRedis(equipmentBoardKey);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String day = simpleDateFormat.format(new Date());
		for(EquipmentBoardPojo ee :list) {
			//获取当日加工时间
			boolean isCheck = (ee.getProcessMaxWorkingTime()==null?0:ee.getProcessMaxWorkingTime()) == 0.0;
			int totalTimeOfMonth = 0 ;
			int totalTimeOfDay = 0;
			//设置当日加工数量
			JSONObject jsonObject = equipmentBoard.get(ee.getEquipmentNo());
			if(null!=jsonObject) {
				EquipmentRecordPojo detail= new EquipmentRecordPojo();
				detail.setCreateTime(day);
				Integer dayCouont = jsonObject.getInteger("count")==null?0:jsonObject.getInteger("count");
				//产能为比例
				dayCouont = (int) this.getProportionCount(dayCouont * 1.0, ee.getStartProportion(), ee.getEndProportion());
				detail.setMachingCount((double) dayCouont);
				List<EquipmentRecordPojo> detailList = ee.getEquipmentRecordPojos();
				if(detailList == null ) {
					detailList = new ArrayList<EquipmentRecordPojo>();
				}
				detailList.add(detail);
				ee.setEquipmentRecordPojos(detailList);
				totalTimeOfDay = this.getOneEquipmentDayTime(ee.getEquipmentNo(), dayList,dayCouont);
				//如果有设置最大的加工时间，工作时间需要另算
				if(!isCheck) {
					double processWorkTime  = ee.getProcessWorkingTime()==null?0.0:ee.getProcessWorkingTime();
					simpleDateFormat = new SimpleDateFormat("yyyy-MM");
					String month = simpleDateFormat.format(new Date());
					for(EquipmentRecordPojo equipmentRecordPojo : detailList) {
						//本月累加
						if(equipmentRecordPojo.getCreateTime() != null && month.equals(equipmentRecordPojo.getCreateTime().substring(0, 7))) {
							totalTimeOfMonth  += (int)(equipmentRecordPojo.getMachingCount() * processWorkTime);
						}
					}
				}else {
					totalTimeOfMonth = (ee.getTotalTimeOfMonth()==null?0:ee.getTotalTimeOfMonth()) + totalTimeOfDay;
				}
			}
			//如果是有设置最大加工时间，时间另算
			ee.setTotalTimeOfDay(totalTimeOfDay);
			ee.setTotalTimeOfMonth(totalTimeOfMonth);
		}
        return list;
    }
    
    /**
     * 获取设备能耗信息
     * @param param
     * @return
     */
    public List<EquipmentBoardPojo> getMachineUseElectric(Map<String, String> param) {
    	 String formatStr = "yyyy-MM-dd";
         String startOfMonth = new DateTime().dayOfMonth().withMinimumValue()
                 .withMillisOfDay(0).toString(formatStr);
         param.put("startOfMonth", startOfMonth);
         //今天之前的数据
         List<EquipmentBoardPojo> list = equipmentMapper.getMachineUseElectric(param);
         //获取当日电量
         List<EnergyBean> energyList= energyService.getEnergyTodayData(param);
         SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
         String day = simpleDateFormat.format(new Date());
 		 for(EquipmentBoardPojo ee :list) {
			EquipmentRecordPojo detail= new EquipmentRecordPojo();
			detail.setCreateTime(day);
			int dayCount = this.getTodayEquipmentCapacity(ee.getEquipmentNo());
			detail.setMachingCount(this.getProportionCount(dayCount * 1.0, ee.getStartProportion(), ee.getEndProportion()) );
			//当日电量
			double  energyUsed = this.getEnergytoDayUsed(energyList,ee.getEnergyId());
			detail.setUseEletic(energyUsed);
			List<EquipmentRecordPojo> detailList = ee.getEquipmentRecordPojos();
			if(detailList == null ) {
				detailList = new ArrayList<EquipmentRecordPojo>();
			}
			detailList.add(detail);
			ee.setEquipmentRecordPojos(detailList);
 		 }
    	 return list;
    }

    /**
     * 获取当日仪表用量
     * @param energyList
     * @param energyId
     * @return
     */
    private double getEnergytoDayUsed(List<EnergyBean> energyList, String energyId) {
    	double x = 0.0;  
    	if(energyList== null || energyList.size()<=0 || null== energyId || "".equals(energyId) ) {
    		return 0 ;
    	}
    	for(EnergyBean e:energyList) {
    		if(energyId.equals(e.getId())) {
    			try {
    				x =  Double.parseDouble(e.getTodayUseCount());
    			}catch(Exception exception ) {
    				x=0;
    			}
    			break;
    		}
    	}
		return x;
	}

	public Map<String, Map<String, Map<String, List<EquipmentDetail>>>> getGroupEquipmentDetails() {
        Map<String, Map<String, Map<String, List<EquipmentDetail>>>> groupEquipmentDetails = new HashMap<>();
        List<EquipmentDetailPojo> equipmentDetailPojos = equipmentMapper.getEquipmentsDetail();
        for (EquipmentDetailPojo equipmentDetailPojo : equipmentDetailPojos) {
            String company = equipmentDetailPojo.getCompany();
            String deptId = equipmentDetailPojo.getDepartment();
            String workShopId = equipmentDetailPojo.getWorkShop();
            List<EquipmentDetail> equipmentDetails = equipmentDetailPojo.getEquipmentDetails();
            groupEquipmentDetails.computeIfAbsent(company, k -> new HashMap<>());
            groupEquipmentDetails.get(company).computeIfAbsent(deptId, k -> new HashMap<>());
            groupEquipmentDetails.get(company).get(deptId).putIfAbsent(workShopId, equipmentDetails);
        }
        return groupEquipmentDetails;
    }

    
    /**
     * 获取设备当日运行时间
     * @param equipmentNos
     * @return
     */
    public  List<EquipmentBoardPojo> getEquipmentDayTime(){
    	List<EquipmentBoardPojo> equipmentTimeOfDaylist=(List<EquipmentBoardPojo>) RedisCache.getDataFromRedis(ReturnStringUtil.EQUIMENT_TOTAL_TIME_OF_DAY);
        if(null==equipmentTimeOfDaylist) {
        	equipmentTimeOfDaylist=equipmentMapper.getEquimentTotalTimeOfDay();
        	RedisCache.setDataToRedis(ReturnStringUtil.EQUIMENT_TOTAL_TIME_OF_DAY, equipmentTimeOfDaylist, ReturnStringUtil.EQUIMENT_TOTAL_TIME_OF_DAY_TIME);
        }
        return equipmentTimeOfDaylist;
    }
    
    /**
     * 获取一个设备的当日运行时间
     * @param equipmentNo
     * @param equipmentTimeOfDaylist
     * @return
     */
    public Integer getOneEquipmentDayTime(String equipmentNo,List<EquipmentBoardPojo> equipmentTimeOfDaylist,Integer capacity) {
    	 if(null==equipmentTimeOfDaylist || equipmentTimeOfDaylist.size()<=0) {
    		return 0;
    	 }
	   	 List<EquipmentBoardPojo> thisEquimentTimeList=equipmentTimeOfDaylist.stream().filter(ee->ee.getEquipmentNo().equals(equipmentNo)).collect(Collectors.toList());
	     if(thisEquimentTimeList.size()<=0) {
	    	 return 0;
	     }else{
	    	 EquipmentBoardPojo ee = thisEquimentTimeList.get(0);
	    	 //如果没有设置最大加工时间,直接返回当日运行时间
	    	 if((ee.getProcessMaxWorkingTime()==null?0:ee.getProcessMaxWorkingTime()) == 0) {
	    		return  ee.getTotalTimeOfDay()==null?0:ee.getTotalTimeOfDay();
	    	 }else {//有设置的话，就返回当日产能 * 工序作业时间
	    		return  (int)(capacity * ee.getProcessWorkingTime()) ;
	    	 }
	     }
    };
    
    
    public Object getEquipmentBoardDynamicData(List<String> equipmentNos) {
        Map<String, JSONObject> data = (Map<String, JSONObject>) RedisCache.getDataFromRedis(equipmentBoardKey);
        Map<String, JSONObject> result = new HashMap<>();
        
        //设置设备当日加工时间
        List<EquipmentBoardPojo> equipmentTimeOfDaylist=this.getEquipmentDayTime();
        if (equipmentNos.size() <= 0) {
            return null;
        }
        for (String equipmentNo : equipmentNos) {
             JSONObject object = data.get(equipmentNo);
             if(object!=null) {
            	 int  startProportion  = 1;
            	 int  endProportion = 1;
            	 for(EquipmentBoardPojo equipmentBoardPojo : equipmentTimeOfDaylist) {
            		 if(equipmentNo.equals(equipmentBoardPojo.getEquipmentNo())) {
            			 startProportion = equipmentBoardPojo.getStartProportion();
            			 endProportion  = equipmentBoardPojo.getEndProportion();
            		 }
            	 }
            	 double dayCount  = (object.getInteger("count") == null ? 0 :object.getInteger("count")) * 1.0;
            	 object.put("totalTimeOfDay", this.getOneEquipmentDayTime(equipmentNo, equipmentTimeOfDaylist, (int)this.getProportionCount(dayCount, startProportion, endProportion)));
            	 object.put("startProportion", startProportion);
            	 object.put("endProportion", endProportion);
             }
            result.put(equipmentNo, object);
        }
        if (result.isEmpty()) {
            return null;
        }
        return result;
    }


    public boolean checkEquipmentNoUnique(Map<String, String> map) {
        List<EquipmentBean> equipmentBeans = getEquipmentByDetail(map);
        return equipmentBeans.size() <= 0;
    }

    public List<EquipmentDetail> getEquipmentDetailByUrlParam(Map<String, String> param) {
        List<EquipmentDetail> equipmentDetails = new ArrayList<>();
        String company = param.get("loginCompany");
        String deptId = param.get("dept");
        String workshopId = param.get("workshop");
        Map<String, Map<String, Map<String, List<EquipmentDetail>>>> groupEquipmentDetails = getGroupEquipmentDetails();
        if (groupEquipmentDetails.get(company) == null) {
            return null;
        }
        if ("ALL".equalsIgnoreCase(deptId)) {
            groupEquipmentDetails.get(company).values()
                    .forEach(deptIdMap -> deptIdMap.values()
                            .forEach(equipmentDetails::addAll));
            return equipmentDetails;
        }
        if ("ALL".equalsIgnoreCase(workshopId)) {
            groupEquipmentDetails.get(company).get(deptId).values()
                    .forEach(equipmentDetails::addAll);
            return equipmentDetails;
        }
        return groupEquipmentDetails.get(company).get(deptId).get(workshopId);
    }

    public void delEquipment(Map map) {
        MachineBean machineBean = machineMapper.getMachineById(map);
        if (machineBean == null) {
            return;
        }
        EquipmentBean equipmentBean = equipmentMapper
                .getEquipmentByMachineId(machineBean.getId());
        machineMapper.remove(machineBean);
        machineRelationProcessMapper
                .delMachineRelationProcessByMachineId(machineBean.getId());
        machineRelationWorkingTimeIntervalMapper
                .delMachineRelationWorkingTimeIntervalByMachineId(machineBean
                        .getId());
        if (equipmentBean != null) {
            energyService.freeOrUseEnergy(equipmentBean.getEnergyId(), EnergyStatus.FREE);
            energyService.freeOrUseEnergy(equipmentBean.getFlowId(), EnergyStatus.FREE);
        }
        equipmentMapper.removeEquipmentAndRecodes(equipmentBean);

    }
    //获取设备总价
    public double getAllEquipmentPrice(Map map) {
    	return equipmentMapper.getAllEquipmentPrice(map);
    }

    /**
     * 获取设备日利用率
     * month  月份
     * @param map
     * @return
     * @throws CloneNotSupportedException 
     */
	public List<EquipmentBoardPojo> getEquipmentDailyUseRate(Map map) throws CloneNotSupportedException {
		//本月不包过当日的设备运行时间状况
		List<EquipmentBoardPojo> list = equipmentMapper.getEquipmentDailyUseRate(map);
		List<EquipmentBoardPojo> todayList = new ArrayList<EquipmentBoardPojo>();
		Map<String,List<EquipmentBoardPojo>> equipmentMap = list.stream().collect(Collectors.groupingBy(EquipmentBoardPojo::getEquipmentNo));
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String toDay = simpleDateFormat.format(new Date());
		//当日设备运行时间
		List<EquipmentBoardPojo> dayList = this.getEquipmentDayTime();
		for(String equipmentNo : equipmentMap.keySet()) {
			EquipmentBoardPojo one=  equipmentMap.get(equipmentNo).get(0);
			EquipmentBoardPojo onEquipmentBoardPojo  = one.clone();
			double toDayCout  = this.getTodayEquipmentCapacity(equipmentNo) * 1.0;
			int  dayTime = this.getOneEquipmentDayTime(equipmentNo, dayList,(int) this.getProportionCount(toDayCout, onEquipmentBoardPojo.getStartProportion(), onEquipmentBoardPojo.getEndProportion()));
			onEquipmentBoardPojo.setTimeName(toDay);
			onEquipmentBoardPojo.setTotalTimeOfDay(dayTime);
			todayList.add(onEquipmentBoardPojo);
		}
		//重新设置
		for(EquipmentBoardPojo equipmentBoardPojo : list ) {
			double  dayCount = equipmentBoardPojo.getDayCount()==null?0:equipmentBoardPojo.getDayCount() * 1.0;
			equipmentBoardPojo.setTotalTimeOfDay(this.getOneDayTotalTime(equipmentBoardPojo,(int)this.getProportionCount(dayCount, equipmentBoardPojo.getStartProportion(), equipmentBoardPojo.getEndProportion())));
		}
		list.addAll(todayList);
		return list;
	}
	
	/**
	 * 
	 * @param equipmentBoardPojo
	 * @return
	 */
	private int  getOneDayTotalTime(EquipmentBoardPojo equipmentBoardPojo,int dayCount) {
		if(null==equipmentBoardPojo) {
			return 0;
		}
		if(0==(equipmentBoardPojo.getProcessMaxWorkingTime()==null?0:equipmentBoardPojo.getProcessMaxWorkingTime())) {
			return equipmentBoardPojo.getTotalTimeOfDay()==null?0:equipmentBoardPojo.getTotalTimeOfDay();
		}else {
			return (int) ((equipmentBoardPojo.getProcessWorkingTime()==null?0:equipmentBoardPojo.getProcessWorkingTime()) * dayCount);
		}
	}

	/**
	 * 获取当日设备产能
	 * @param equipmentNo
	 * @param startProportion 
	 * @param endProportion 
	 * @return
	 */
	private int getTodayEquipmentCapacity(String equipmentNo) {
		//获取当日产能 
        Map<String, JSONObject> equipmentBoard = (Map<String, JSONObject>) RedisCache.getDataFromRedis(equipmentBoardKey);
		JSONObject jsonObject = equipmentBoard.get(equipmentNo);
		if(null!=jsonObject) {
			int    dayCount = (jsonObject.getInteger("count")==null?0:jsonObject.getInteger("count"));
			return dayCount;
		}else {
			return 0;
		}		
	}

	/**
     * 获取设备月利用率
     * month  月份
     * @param map
     * @return
     */
	public List<EquipmentBoardPojo> getEquipmentMonthUseRate(Map map) {
		SimpleDateFormat simpleDateFormat= new SimpleDateFormat("yyyy-MM");
		String month = simpleDateFormat.format(new Date());
		List<EquipmentBoardPojo> list= equipmentMapper.getEquipmentMonthUseRate(map);
		//当日设备运行时间
		List<EquipmentBoardPojo> dayList = this.getEquipmentDayTime();
		for(EquipmentBoardPojo ee:list) {
			ee.setTotalTimeOfDay(this.getOneDayTotalTime(ee,(int)this.getProportionCount((ee.getDayCount() == null ? 0:ee.getDayCount()) * 1.0 , ee.getStartProportion(), ee.getEndProportion())));
			if(month.equals(ee.getTimeName())) {
			    double dayCount = this.getTodayEquipmentCapacity(ee.getEquipmentNo()) * 1.0;
				int  dayTime = this.getOneEquipmentDayTime(ee.getEquipmentNo(), dayList,(int)this.getProportionCount(dayCount, ee.getStartProportion(), ee.getEndProportion()));
				ee.setTotalTimeOfDay((ee.getTotalTimeOfDay()==null?0:ee.getTotalTimeOfDay())+dayTime);
			}
		}
		return list;
	}

	/**
	 * 通过物联网卡id 获取
	 * @param internetThingsCard
	 * @return
	 */
	public String getEquimentNoByInternetThingsCard(String internetThingsCard) {
		return equipmentMapper.getEquimentNoByInternetThingsCard(internetThingsCard);
	}

	/**
	 * 
	 * @param map
	 * @return
	 */
	public List<EquipmentAlarmCodeBean> getEquipmentAlarmCode(Map map) {
		List<EquipmentAlarmCodeBean> list=equipmentMapper.getEquipmentAlarmCode(map);
		return list;
	}

	
	/**
	 * jsonArray
	 * 添加设备警报设置
	 * @param map
	 * @return
	 */
	public String addEquipmentAlarmCode(Map map) {
		StringUtil.checkIsTrue(map, "jsonArray", "未获取到参数");
		String jsonString=map.get("jsonArray").toString();
		JSONArray jsonArray= JSONArray.fromObject(jsonString);
		List<EquipmentAlarmCodeBean> list=(List<EquipmentAlarmCodeBean>) JSONArray.toCollection(jsonArray, EquipmentAlarmCodeBean.class);
		Assert.isTrue(list.size()>0,"未获取到参数");
		List<EquipmentAlarmCodeBean> oldList=this.getEquipmentAlarmCode(map);
		oldList.addAll(list);
		Map<String, List<EquipmentAlarmCodeBean>> groupMap=oldList.stream().collect(Collectors.groupingBy(EquipmentAlarmCodeBean::getNameAndCode));
		for(String key:groupMap.keySet()) {
			Assert.isTrue(groupMap.get(key).size()<=1,key);
		}
		map.put("list", list);
		int row=equipmentMapper.addEquipmentAlarmCode(map);
		Assert.isTrue(row>0,ReturnStringUtil.ADD_ERROR);
		return ReturnStringUtil.ADD_SUCCESS;
	}

	
	/**
	 * 删除设备警报详情
	 * @param map
	 * @return
	 */
	public String deleteEquipmentAlarmCode(Map map) {
		StringUtil.checkIsTrue(map, "jsonArray", "未获取到参数");
		String jsonString=map.get("jsonArray").toString();
		JSONArray jsonArray= JSONArray.fromObject(jsonString);
		List<EquipmentAlarmCodeBean> list=(List<EquipmentAlarmCodeBean>) JSONArray.toCollection(jsonArray, EquipmentAlarmCodeBean.class);
		Assert.isTrue(list.size()>0,"未获取到参数");
		map.put("list", list);
		equipmentMapper.deleteEquipmentAlarmCode(map);
		return ReturnStringUtil.DELETE_SUCCESS;
	}
	
	/**
	 * 修改警报信息
	 * @param map
	 * @return
	 */
	public String updateEquipmentAlarmCode(Map map) {
		StringUtil.checkIsTrue(map, "jsonArray", "未获取到参数");
		String jsonString=map.get("jsonArray").toString();
		JSONArray jsonArray= JSONArray.fromObject(jsonString);
		List<EquipmentAlarmCodeBean> list=(List<EquipmentAlarmCodeBean>) JSONArray.toCollection(jsonArray, EquipmentAlarmCodeBean.class);
		Assert.isTrue(list.size()>0,"未获取到参数");
		map.put("list", list);
		int  row=equipmentMapper.updateEquipmentAlarmCode(map);
		return ReturnStringUtil.UPDATE_SUCCESS;
	}

	/**
	 * 获取设备日产能
	 * @param map
	 * @return
	 */
	public List<ProductionExceptionBean> getMachineCapacity(Map map) {
		List<ProductionExceptionBean>  returnList= new ArrayList<ProductionExceptionBean>();;
		String month = map.get("month")==null?"":map.get("month").toString();
		SimpleDateFormat simpleDateFormat= new SimpleDateFormat("yyyy-MM");
		String  thisMonth= simpleDateFormat.format(new Date());
		simpleDateFormat= new SimpleDateFormat("yyyy-MM-dd");
		String day = simpleDateFormat.format(new Date());
		returnList = equipmentMapper.getMachineCapacity(map);
		if(thisMonth.equals(month)) {//如果是本月,只获取当天的数据
			//当天设备
			List<EquipmentRecordPojo> dayEquipmentCapacityList= this.getDayEquipmentCapacityList();
			for(ProductionExceptionBean pp:returnList) {
				DutyBean dd  = new DutyBean();
				dd.setDelayTime(day);
				dd.setCapacity((long)this.getTodayProcessCapacity(pp.getProcessId(), dayEquipmentCapacityList));
			    List<DutyBean> detailList = pp.getListDuty();
			    if(null == detailList) {
			    	detailList = new ArrayList<DutyBean>();
			    }
			    detailList.add(dd);
			    pp.setListDuty(detailList);
			}
		}
		return returnList;
	}

	/**
	 * 获取设备工序产能
	 * @param map
	 * @return
	 */
	public List<MachinepRrocessCapacityBean> getMachieProcessCapacity(Map map) {
		List<MachinepRrocessCapacityBean> list=equipmentMapper.getMachieProcessCapacity(map);
		List<String> equipmentNoList=list.stream().map(MachinepRrocessCapacityBean::getEquipmentNo).collect(Collectors.toList());
		list=this.setDayTime(list);
		map.put("equipmentNoList", equipmentNoList);
		List<DayCapacity> dayCapacityList= this.getEquipmentMonthCapacityDatail(map,equipmentNoList);
		dayCapacityList=dayCapacityList.stream().filter(pp->equipmentNoList.contains(pp.getEquipmentNo())).collect(Collectors.toList());
		Map<String,List<DayCapacity>> groupMap = dayCapacityList.stream().collect(Collectors.groupingBy(DayCapacity::getEquipmentNo));
		for(MachinepRrocessCapacityBean ee:list) {
			List<DayCapacity> detailList = groupMap.get(ee.getEquipmentNo());
			detailList = detailList ==null ? new ArrayList<DayCapacity>():detailList;
			for(DayCapacity ss :detailList) {
				double capacity = (ss.getCapacity()==null?0:ss.getCapacity()) * 1.0;
				ss.setCapacity((int)this.getProportionCount(capacity, ee.getStartProportion(), ee.getEndProportion()));
			}
			ee.setDayList(detailList);
		}
		return list;
	}
	
	/**
	 * 设置设备当日运行时间
	 * @param list
	 * @param equipmentNoList
	 * @return
	 */
	private List<MachinepRrocessCapacityBean> setDayTime(List<MachinepRrocessCapacityBean> list) {
		List<EquipmentBoardPojo> dayList = this.getEquipmentDayTime();
		for(MachinepRrocessCapacityBean  ee :list) {
			  double dayCout  = this.getTodayEquipmentCapacity(ee.getEquipmentNo()) * 1.0;
			  int  dayTime = this.getOneEquipmentDayTime(ee.getEquipmentNo(), dayList,(int) this.getProportionCount(dayCout, ee.getStartProportion(), ee.getEndProportion()));
			  ee.setDayTime(dayTime);
			  if((ee.getProcessMaxWorkingTime()==0?0:ee.getProcessMaxWorkingTime()) == 0) {
				  double  yearCount = ee.getYearCount() == null?0.0:ee.getYearCount();
				  yearCount=this.getProportionCount(yearCount, ee.getStartProportion(), ee.getEndProportion());
				  double monthCount =ee.getMonthCount()==null?0.0:ee.getMonthCount();
				  monthCount = this.getProportionCount(monthCount,ee.getStartProportion(), ee.getEndProportion());
		    	  ee.setYearTime((int) (yearCount * (ee.getProcessWorkingTime() == null?0:ee.getProcessWorkingTime()))+dayTime);
		          ee.setMonthTime((int) (monthCount * (ee.getProcessWorkingTime()==null?0:ee.getProcessWorkingTime()))+dayTime) ;
			  }else {
		    	  ee.setYearTime((ee.getYearTime()==null?0:ee.getYearTime())+dayTime);
		    	  ee.setMonthTime((ee.getMonthTime()==null?0:ee.getMonthTime())+dayTime);
		      }
		}
		return list;
	}

	/**
	 * 获取设备当月产能明细
	 * @param map
	 * @param equipmentNoList 
	 * @return
	 */
	private List<DayCapacity> getEquipmentMonthCapacityDatail(Map map, List<String> equipmentNoList) {
		String month = map.get("month")==null?"":map.get("month").toString();
		SimpleDateFormat simpleDateFormat= new SimpleDateFormat("yyyy-MM");
		String  thisMonth= simpleDateFormat.format(new Date());
		List<DayCapacity>  returnList= returnList = equipmentMapper.getEquipmentMonthCapacityDatail(map);
		if(thisMonth.equals(month)) {//如果是本月,只获取当天的数据
			simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
			String day=simpleDateFormat.format(new Date());
			for(String no:equipmentNoList) {
				DayCapacity dd = new DayCapacity();
				dd.setCapacity(this.getTodayEquipmentCapacity(no));
				dd.setDelayTime(day);
				dd.setEquipmentNo(no);
				returnList.add(dd);
			}
		}
		return returnList;
	}

	/**
	 * 获取工序能耗数据
	 * @param map
	 * @return
	 */
	public List<EquipmentBoardPojo> getProcessConsumptionData(Map map) {
		 String formatStr = "yyyy-MM-dd";
         String startOfMonth = new DateTime().dayOfMonth().withMinimumValue()
                 .withMillisOfDay(0).toString(formatStr);
         map.put("startOfMonth", startOfMonth);
         List<EquipmentBoardPojo> list= equipmentMapper.getProcessConsumptionData(map);
         //获取当日电量
         List<EnergyBean> energyList= energyService.getEnergyTodayData(map);
         //获取当日工序产能
         List<EquipmentRecordPojo> dayEquipmentCapacityList= this.getDayEquipmentCapacityList();
         SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
         String day = simpleDateFormat.format(new Date());
 		 for(EquipmentBoardPojo ee :list) {
			EquipmentRecordPojo detail= new EquipmentRecordPojo();
			detail.setCreateTime(day);
			//当日电量
			double  energyUsed = this.getEnergytoDayUsed(energyList,ee.getEnergyId());
			double  processCapacity = this.getTodayProcessCapacity(ee.getProcessId(),dayEquipmentCapacityList);
			detail.setUseEletic(energyUsed);
			detail.setMachingCount(processCapacity);
			List<EquipmentRecordPojo> detailList = ee.getEquipmentRecordPojos();
			if(detailList == null ) {
				detailList = new ArrayList<EquipmentRecordPojo>();
			}
			detailList.add(detail);
			ee.setEquipmentRecordPojos(detailList);
 		 }
    	return list;
	}

	
	/**
	 * 获取当日工序产能
	 * @param processId
	 * @param dayEquipmentCapacityList
	 * @return
	 */
	private double getTodayProcessCapacity(String processId, List<EquipmentRecordPojo> dayEquipmentCapacityList) {
	    if(dayEquipmentCapacityList == null || processId == null ) {
	    	return 0;
	    }
		Double xx = dayEquipmentCapacityList.stream().filter(pp->processId.equals(pp.getProcessId())).mapToDouble(EquipmentRecordPojo::getMachingCount).sum();
		return xx;
	}

	/**
	 * 获取今日工序产能
	 * @return
	 */
	private List<EquipmentRecordPojo> getDayEquipmentCapacityList() {
		/**
		 * 获取今日设备加工记录
		 */
		List<EquipmentRecordPojo> list = equipmentMapper.getToDayRecordData();
		List<EquipmentRecordPojo> returnList = this.getEquipmentProcessCapacity(list);
		for(EquipmentRecordPojo ee : returnList) {
			ee.setMachingCount(this.getProportionCount(ee.getMachingCount(),ee.getStartProportion(),ee.getEndProportion()));
		}
		return returnList;
	}

	/**
	 * 计算比例产能
	 * @param machingCount
	 * @param startProportion
	 * @param endProportion
	 * @return
	 */
	private double getProportionCount(Double machingCount, Integer startProportion, Integer endProportion) {
		if(machingCount==null) {
			return 0.0;
		}
		startProportion = startProportion==null?1:startProportion;
		endProportion = endProportion==null?1:endProportion;
		return Math.ceil(machingCount * startProportion / endProportion);
	}

	/**
	 * 统计设备产能
	 */
	public List<EquipmentRecordPojo>  statisticsEquipmentCapacity(List<EquipmentRecordPojo> list) {
	   	//获取要统计的数据
		List<EquipmentRecordPojo> returnList=new ArrayList<EquipmentRecordPojo>();
//	   	List<EquipmentRecordPojo> list = equipmentMapper.getRecordData();
	   	//按设备编号分组
	   	Map<String,List<EquipmentRecordPojo>> equipNoGroup = list.stream().collect(Collectors.groupingBy(EquipmentRecordPojo::getEquipmentNo));
	   	for(String equipmentNo: equipNoGroup.keySet()) {
	   		List<EquipmentRecordPojo> onList= equipNoGroup.get(equipmentNo);
	   		Map<String, List<EquipmentRecordPojo>> dayMap = onList.stream().collect(Collectors.groupingBy(EquipmentRecordPojo::getDay));
	   		for(String day:dayMap.keySet()) {
 	   			double dayCount = 0 ;//一天的产能
	   			EquipmentRecordPojo equipmentRecordPojo = new EquipmentRecordPojo();
	   			List<EquipmentRecordPojo> dayList=dayMap.get(day);
	   			Collections.sort(dayList, Comparator.comparing(EquipmentRecordPojo::getCreateTime));
	   			List<Double> capacityList= dayList.stream().map(EquipmentRecordPojo::getMachingCount).collect(Collectors.toList());
	   			double startCount = capacityList.get(0);
	   	    	double beforeCount  = capacityList.get(0);
	   	    	int  index= capacityList.size()-1;
	   	    	for(int i = 0;i<=index;i++) {
	   	    		double thisCount= capacityList.get(i);
	   	    		if(thisCount<beforeCount) {
	   	    			dayCount += beforeCount - startCount  + 1;
	   	    			startCount =thisCount; 
	   	    		}
	   	    		beforeCount = thisCount;
	   	    		if(i==index) {
	   	    			dayCount += beforeCount - startCount  + 1;
	   	    		}
	   	    	}
	   	    	equipmentRecordPojo.setEquipmentNo(equipmentNo);
	   	    	equipmentRecordPojo.setDay(day);
	   	    	equipmentRecordPojo.setMachingCount(dayCount);
	   	    	equipmentRecordPojo.setCompany(dayList.get(0).getCompany());
	   	    	returnList.add(equipmentRecordPojo);
	   	    }
	   	}
	   	int size= returnList.size();
	   	int  length=(int) Math.ceil(size/300.0);
	   	for(int i=0;i<length;i++ ) {
	   		List<EquipmentRecordPojo> subList= null;
	   		if(i==length-1) {
	   			subList = returnList.subList(i*300, size);
	   		}else {
	   			subList = returnList.subList(i*300, (i+1)*300);
	   		}
	   		equipmentMapper.statisticsEquipmentCapacity(subList);
	   	}
	   	return returnList;
	}
	
	
	
	/**
	 * 统计设备工序产能
	 */
	public List<EquipmentRecordPojo>  statisticsEquipmentProcessCapacity(List<EquipmentRecordPojo> list) {
		//获取要统计的数据
//		List<EquipmentRecordPojo> list = equipmentMapper.getRecordData();
		List<EquipmentRecordPojo> returnList= this.getEquipmentProcessCapacity(list);
		int size= returnList.size();
		int  length=(int) Math.ceil(size/280.0);
		for(int i=0;i<length;i++ ) {
			List<EquipmentRecordPojo> subList= null;
			if(i==length-1) {
				subList = returnList.subList(i*280, size);
			}else {
				subList = returnList.subList(i*280, (i+1)*280);
			}
			equipmentMapper.statisticsEquipmentProcessCapacity(subList);
		}
		return returnList;
	}
	
	
	private List<EquipmentRecordPojo> getEquipmentProcessCapacity(List<EquipmentRecordPojo> list) {
		List<EquipmentRecordPojo> returnList = new ArrayList<EquipmentRecordPojo>();
		//按设备编号分组
		Map<String,List<EquipmentRecordPojo>> equipNoGroup = list.stream().collect(Collectors.groupingBy(EquipmentRecordPojo::getEquipmentNo));
		for(String equipmentNo: equipNoGroup.keySet()) {
			List<EquipmentRecordPojo> onList= equipNoGroup.get(equipmentNo);
			Map<String, List<EquipmentRecordPojo>> dayMap = onList.stream().collect(Collectors.groupingBy(EquipmentRecordPojo::getDay));
			for(String day:dayMap.keySet()) {
				//工序数量map
				Map<String, Double> oneDayMap = new HashMap<String,Double>();
				List<EquipmentRecordPojo> dayList=dayMap.get(day);
				Collections.sort(dayList, Comparator.comparing(EquipmentRecordPojo::getCreateTime));
				String processId = dayList.get(0).getProcessId();//第一个工序id
				double  processCount  = 0;
				double startCount = dayList.get(0).getMachingCount();
				double beforeCount  = dayList.get(0).getMachingCount();
				int  index= dayList.size()-1;
				for(int i = 0;i<=index;i++) {
					String thisProcessId = dayList.get(i).getProcessId();
					double thisCount= dayList.get(i).getMachingCount();
					if(thisCount<beforeCount) {
						processCount += beforeCount - startCount  + 1;
						startCount =thisCount; 
					}
					beforeCount = thisCount;
					/**
					 * 工序有变从零开始计数
					 */
					if(!processId.equals(thisProcessId)) {
						oneDayMap.put(processId,(oneDayMap.get(processId)==null?0:oneDayMap.get(processId)) + processCount );
						processCount= 0.0;
						processId = thisProcessId;
					}
					if(i==index) {
						processCount += beforeCount - startCount  + 1;
						//如果工序没有变化保存
						if(processId.equals(thisProcessId)) {
							oneDayMap.put(processId,(oneDayMap.get(processId)==null?0:oneDayMap.get(processId)) + processCount );
						}
					}
				}
				List<EquipmentRecordPojo> onDayList = new ArrayList<EquipmentRecordPojo>();
				for(String proId:oneDayMap.keySet()) {
					EquipmentRecordPojo equipmentRecordPojo = new EquipmentRecordPojo();
					equipmentRecordPojo.setEquipmentNo(equipmentNo);
					equipmentRecordPojo.setDay(day);
					equipmentRecordPojo.setCompany(dayList.get(0).getCompany());
					equipmentRecordPojo.setMachingCount(oneDayMap.get(proId));
					equipmentRecordPojo.setProcessId(proId);
					equipmentRecordPojo.setStartProportion(dayList.get(0).getStartProportion());
					equipmentRecordPojo.setEndProportion(dayList.get(0).getEndProportion());
					onDayList.add(equipmentRecordPojo);
				}
				returnList.addAll(onDayList);
			}
		}
		return returnList;
	}

	/**
	 * 定时统计昨日设备运行状态
	 */
	public void setEquipmentStateTime() {
		List<EquipmentTimeRecordBean> list = equipmentMapper.getNotHaveEndTimeEquipmentRecord(); //获取没有结束时间的设备运行记录
		SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:01.000");
		String toDayStartTime = sDateFormat.format(new Date());
		List<String> idList= list.stream().map(EquipmentTimeRecordBean::getId).collect(Collectors.toList());
	    if(list.size() > 0) {
	    	equipmentMapper.updateEquipmentTimeReordEndTime(idList,toDayStartTime);//将结束时间补齐，结束时间为今天第一分钟
	    	equipmentMapper.insertEquipmentTimeReordStartTime(list,toDayStartTime);//插入新的记录，开始时间为今天第一分钟
	    }
		equipmentMapper.statisticsEquipmentTime();//统计昨天设备运行时间
	}
	
	/**
	 * 设置设备报工数据
	 */
	public  List<ReportBean> setEquipmentReportOrderData(List<EquipmentRecordPojo> list) {
		  List<ReportBean> reportList = new ArrayList<ReportBean>();
		  String dayStr = TimeAndUnix.getBeforeDay(-1, " 00:00:00.000");
		  String timeStr = TimeAndUnix.getBeforeDay(-1, " 23:59:58.000");
		  //设备报工工序
		  List<String> processIdList = equipmentMapper.getEquipmentReportProcessId();
		  if(processIdList.size()>0) {
			  //工序是设备报工,订单编号,加工对象,创建人都不为空
			  List<EquipmentRecordPojo> filterList = list.stream().filter(dd->processIdList.contains(dd.getProcessId()) && !"".equals(dd.getMachinig()) && !"".equals(dd.getOrderId()) && !"".equals(dd.getCreateUser())).collect(Collectors.toList());
              //获得人,订单,工序,加工对象  合并后的list		     
			  List<EquipmentRecordPojo> groupList = this.getUserOrderProcessReportList(filterList);
			  if(filterList.size()>0) {
				  Map<String, List<EquipmentRecordPojo>> orderMap = groupList.stream().collect(Collectors.groupingBy(EquipmentRecordPojo::getOrderId));
				  for(String orderId:orderMap.keySet()) {
					  List<EquipmentRecordPojo> ontOrderList = orderMap.get(orderId);
					  Map<String,List<EquipmentRecordPojo>> processMap = ontOrderList.stream().collect(Collectors.groupingBy(EquipmentRecordPojo::getProcessId));
					  for(String processId:processMap.keySet()) {
						  List<EquipmentRecordPojo> processList = processMap.get(processId);
						  Collections.sort(processList, Comparator.comparing(EquipmentRecordPojo::getCreateTime));
						  ReportBean orderProcessReport = equipmentMapper.getOrderProcessReport(processId,orderId);
						  //如果有人工报过工的，不需要统计设备报工
						  if(orderProcessReport.getQualified()==0) {orderProcessReport.setIsMachineReport(1);}
						  if(orderProcessReport.getIsMachineReport() == null || 0 == orderProcessReport.getIsMachineReport()) {
							  continue;
						  }
						  //遍历
						  for(EquipmentRecordPojo ss:processList) {
							  ReportBean reportBean = new ReportBean();
							  int machingCount  = (int) Math.ceil(ss.getMachingCount());
							  //报工数已经超过了投料数没超过继续往下算
							  if(machingCount + orderProcessReport.getQualified() > orderProcessReport.getOrderCount()) {
								  if(orderProcessReport.getOrderCount()-orderProcessReport.getQualified()>0) {
									  reportBean.setQualified(orderProcessReport.getOrderCount()-orderProcessReport.getQualified());
									  reportBean.setOrderId(ss.getOrderId());
									  reportBean.setProcedur(ss.getProcessId());
									  reportBean.setTouchPeople(ss.getCreateUser());
									  reportBean.setMachining(ss.getMachinig());
									  reportBean.setCompany(ss.getCompany());
									  reportBean.setWorkShopId(ss.getWorkShopId());
									  reportBean.setTime(dayStr);
									  reportBean.setTouchTime(timeStr);
									  reportBean.setTypeId(StringUtil.getUUID());
									  reportList.add(reportBean);
								  }
								  break;
							  }else {
								  reportBean.setQualified(machingCount);
								  reportBean.setOrderId(ss.getOrderId());
								  reportBean.setProcedur(ss.getProcessId());
								  reportBean.setTouchPeople(ss.getCreateUser());
								  reportBean.setMachining(ss.getMachinig());
								  reportBean.setCompany(ss.getCompany());
								  reportBean.setWorkShopId(ss.getWorkShopId());
								  reportBean.setTime(dayStr);
								  reportBean.setTouchTime(timeStr);
								  reportBean.setTypeId(StringUtil.getUUID());
								  reportList.add(reportBean);
								  orderProcessReport.setQualified(orderProcessReport.getQualified()+machingCount);
							  }
						  }
					  }
				  }
			  }
		  }
		  if(reportList.size()>0) {
			  int size= reportList.size();
			  int  length=(int) Math.ceil(size/170.0);
			  for(int i=0;i<length;i++ ) {
				List<ReportBean> subList= null;
				if(i==length-1) {
					subList = reportList.subList(i*170, size);
				}else {
					subList = reportList.subList(i*170, (i+1)*170);
				}
				equipmentMapper.insertEquipmentReport(subList);
			}
		  }
		  return reportList;
	}

	/**
	 * 获取用户订单工序设备报工情况
	 * @param filterList
	 * @return
	 */
	private List<EquipmentRecordPojo> getUserOrderProcessReportList(List<EquipmentRecordPojo> filterList) {
		List<EquipmentRecordPojo> returnList = new ArrayList<EquipmentRecordPojo>();
		//按设备编号汇总
		Map<String,List<EquipmentRecordPojo>> equipmentGroup = filterList.stream().collect(Collectors.groupingBy(EquipmentRecordPojo::getEquipmentNo));
		for(String equipmentNo: equipmentGroup.keySet()) {
			List<EquipmentRecordPojo> onEquipmentList= equipmentGroup.get(equipmentNo);
			Collections.sort(onEquipmentList, Comparator.comparing(EquipmentRecordPojo::getCreateTime));
			//工序数量map
			Map<String, Double> countMap = new HashMap<String, Double>();
			Map<String, String> timeMap = new HashMap<String, String>();
			
			//第一个组合键
			String groupStr = onEquipmentList.get(0).getEquipmentReportStr();
			double  groupCount  = 0;
			double startCount = onEquipmentList.get(0).getMachingCount();
			double beforeCount  = onEquipmentList.get(0).getMachingCount();
			int  index= onEquipmentList.size()-1;
			for(int i = 0;i<=index;i++) {
				String thisGroupStr = onEquipmentList.get(i).getEquipmentReportStr();
				double thisCount= onEquipmentList.get(i).getMachingCount();
				if(thisCount<beforeCount) {
					groupCount += beforeCount - startCount  + 1;
					startCount =thisCount; 
				}
				beforeCount = thisCount;
				/**
				 * 工序有变从零开始计数
				 */
				if(!groupStr.equals(thisGroupStr)) {
					timeMap.put(groupStr, timeMap.get(groupStr) == null?onEquipmentList.get(i).getCreateTime():timeMap.get(groupStr));
					countMap.put(groupStr,(countMap.get(groupStr)==null?0:countMap.get(groupStr)) + groupCount );
					groupCount= 0.0;
					groupStr = thisGroupStr;
				}
				if(i==index) {
					groupCount += beforeCount - startCount  + 1;
					//如果工序没有变化保存
					if(groupStr.equals(thisGroupStr)) {
						timeMap.put(groupStr, timeMap.get(groupStr) == null?onEquipmentList.get(i).getCreateTime():timeMap.get(groupStr));
						countMap.put(groupStr,(countMap.get(groupStr)==null?0:countMap.get(groupStr)) + groupCount );
					}
				}
			}
			List<EquipmentRecordPojo> onDayList = new ArrayList<EquipmentRecordPojo>();
			for(String dd:countMap.keySet()) {
			    String [] groupArray = dd.split("-");
			    EquipmentRecordPojo equipmentRecordPojo = new EquipmentRecordPojo();
			    equipmentRecordPojo.setOrderId(groupArray[0]);
				equipmentRecordPojo.setCreateUser(groupArray[1]);
				equipmentRecordPojo.setProcessId(groupArray[2]);
				equipmentRecordPojo.setMachinig(groupArray[3]);
				equipmentRecordPojo.setCreateTime(timeMap.get(dd));
				equipmentRecordPojo.setCompany(onEquipmentList.get(0).getCompany());
				equipmentRecordPojo.setWorkShopId(onEquipmentList.get(0).getWorkShopId());
				equipmentRecordPojo.setMachingCount(this.getProportionCount(countMap.get(dd),onEquipmentList.get(0).getStartProportion(),onEquipmentList.get(0).getEndProportion()));
				onDayList.add(equipmentRecordPojo);
			}
		returnList.addAll(onDayList);
		}
		List<EquipmentRecordPojo> rrList = new ArrayList<EquipmentRecordPojo>();
		Map<String, List<EquipmentRecordPojo>> mm = returnList.stream().collect(Collectors.groupingBy(EquipmentRecordPojo::getEquipmentReportStr));
		//时间取最小，人，订单，工序，加工对象分组，数量累加
		for(String dd : mm.keySet()) {
			List<EquipmentRecordPojo> onGroup = mm.get(dd);
			Collections.sort(onGroup, Comparator.comparing(EquipmentRecordPojo::getCreateTime));
			EquipmentRecordPojo ee= new EquipmentRecordPojo();
			EquipmentRecordPojo equipmentRecordPojo = new EquipmentRecordPojo();
			ee.setOrderId(onGroup.get(0).getOrderId());
			ee.setCreateUser(onGroup.get(0).getCreateUser());
			ee.setProcessId(onGroup.get(0).getProcessId());
			ee.setMachinig(onGroup.get(0).getMachinig());
			ee.setCreateTime(onGroup.get(0).getCreateTime());
			ee.setCompany(onGroup.get(0).getCompany());
			ee.setWorkShopId(onGroup.get(0).getWorkShopId());
			ee.setMachingCount(onGroup.stream().mapToDouble(EquipmentRecordPojo::getMachingCount).sum());
			rrList.add(ee);
		 }
	     return rrList;
   }
	
	
//	List<EquipmentRecordPojo> returnList = equipmentMapper.getRecordData();
//	try {
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//		String toDay = sdf.format(new Date());//今天
//		Map<String, JSONObject> equipmentBoard = (Map<String, JSONObject>) RedisCache.getDataFromRedis("equipmentBoard");
//		for(String equipmentNo : equipmentBoard.keySet()) {
//			JSONObject jsonObject = equipmentBoard.get(equipmentNo);
//			for(EquipmentRecordPojo ee:returnList) {
//				if(equipmentNo.equals(ee.getEquipmentNo())) {
//					jsonObject.put("count", (int)(double)ee.getMachingCount());
//					equipmentBoard.put(equipmentNo, jsonObject);
//					break;
//				}
//			}
////			String oldDay = jsonObject.getString("day");
////			if(!toDay.equals(oldDay)) {//如果日期不是今天
////				jsonObject.put("day", toDay);
////				jsonObject.put("count", 0);
////    		}
//		}
//		RedisCache.setDataToRedis("equipmentBoard", equipmentBoard, null);
//	}catch(Exception e) {
//		
//	}
}
